$('.right-titleicon').on("click", function(e) {
	projectVM.showMenulist()
})
// mui.init({
// beforeback: function() {
// var list = plus.webview.currentWebview().opener();
// 　　　　 //触发父页面的自定义事件(refresh),从而进行刷新
// mui.fire(list, 'refresh');
// //返回true,继续页面关闭逻辑
// return true;
// }
// });
//厂长审批的钥匙类型
var keyTypeStation = ['4', '5', '6'] //生产经理审批的钥匙类行
var keyTypeManage = ['6'] //厂长审批的钥匙类型
var mask = mui.createMask(() => {
	return projectVM.isCloseMask;
}); //callback为用户点击蒙版时自动执行的回调；
projectVM = new Vue({
	el: "#content",
	components: {
		personselect,
		workticket
	},
	data: {
		userInfo: '',
		dutyInfo: '',
		remark: '',
		isSingle: true,
		nowDate: '',
		menuList: [{
			name: '借用',
			path: 'borrow.html'
		}, {
			name: '归还',
			path: 'return.html'
		}, {
			name: '列表',
			path: 'index.html'
		}, {
			name: '我值班'
		}, ],
		keyOperateId: '',
		saveType: 'I',
		keyList: [],
		user: '',
		keyManageId: '',
		edit: false,
		showSubmit: false,
		onStatus: '',
		keyNum: '',
		result: '',
		showMenu: false,
		showMorebtn: false,
		advance: '',
		showAdd: false,
		show_popup: false,
		param: '',
		keyList: [],
		isCloseMask: false
	},
	mounted: function() {

		this.userInfo = JSON.parse(localStorage.getItem("neiosUser"))
		this.user = JSON.parse(localStorage.getItem('neiosUser'))
		this.detail = JSON.parse(localStorage.getItem('keyOperate'))
		localStorage.removeItem('keyOperate')
		if (localStorage.getItem('scanKeyid')) {
			this.keyManageId = localStorage.getItem('scanKeyid')
			this.confrimKeyinfo()
			localStorage.removeItem('scanKeyid')
		}
		this.getDuty()
		if (this.detail != null) {
			this.edit = true
			this.saveType = 'U'
			this.nowDate = this.detail.operateTime
			this.$refs.personselect.person = '[' + this.detail.operateStaffCode + ']' + this.detail
				.operateStaffName
			this.$refs.personselect.personids = this.detail.operateStaffCode
			this.getKeylist()
			this.remark = this.detail.remark
			this.keyOperateId = this.detail.keyOperateId
		} else {
			this.$refs.personselect.person = '[' + this.user.userId + ']' + this.user.name
			this.$refs.personselect.personids = this.user.userId
			this.keyOperateId = mui.neiosCommon.getUuidv4()
			this.getDate()
		}
	},
	methods: {
		// 解决mui遮罩层点击关闭bug
		maskShow(){
		  this.isCloseMask = false;
		  mask.show();
		},
		maskClose(ms){
			ms = !ms ? 0 : ms;
			setTimeout(()=>{
				this.isCloseMask = true;
				mask.close()
			},ms)
			
		},
		//选择我是值班人
		chooseDuty() {
			var that = this
			if (this.dutyInfo.dutyStaffCode == this.userInfo.userId) {
				mui.toast('你已经是值班人')
				return
			}
			console.log(e, '==')
			var btnArray = ['否', '是'];
			mui.confirm('确定设置自己为值班人吗', '提示', btnArray, function(e) {

				if (e.index == 1) {
					that.setDuty()

				} else {

				}
			})
		},
		//无值班人设置新值班人
		setNewDuty(e) {
			if ((e == 0 && this.$refs.personselectDuty.person == '') || e == 1) {
				return
			}
			var url = '/app/currentEntry/keyOperate/saveDutyStaff'
			var that = this
			let param = {
				currentUser: this.userInfo,
				dutyStaffCode: that.$refs.personselectDuty.personids,
				dutyStaffName: that.$refs.personselectDuty.person.split(']')[1]
			}
			mui.neiosRequst.httpRequst(url, param,
				function(data) {

				},
				function() {
					console.log("查询失败!");
				})
		},
		//设置值班人
		setDuty() {
			var url = '/app/currentEntry/keyOperate/saveDutyStaff'
			var that = this
			let param = {
				currentUser: this.userInfo,
				dutyStaffCode: this.userInfo.userId,
				dutyStaffName: this.userInfo.name
			}
			mui.neiosRequst.httpRequst(url, param,
				function(data) {
					that.onStatus = true
				},
				function() {
					console.log("查询失败!");
				})
		},
		//获取值班人
		getDuty() {
			var url = '/app/currentEntry/keyOperate/getDutyStaff'
			var that = this
			let param = {
				currentUser: this.userInfo
			}
			mui.neiosRequst.httpRequst(url, param,
				function(data) {
				console.log("获取值班人参数========",JSON.stringify(param))
				console.log("获取值班人信息========",JSON.stringify(data))
					if (data.data == null) {
						that.dutyInfo = {
							dutyStaffCode: '',
							dutyStaffName: ''
						}
					} else {
						that.dutyInfo = data.data
						that.$refs.personselectDuty.person = '[' + that.dutyInfo.dutyStaffCode + ']' + that
							.dutyInfo.dutyStaffName
						that.$refs.personselectDuty.personids = that.dutyInfo.dutyStaffCode
					}

					if (that.dutyInfo.dutyStaffCode == that.userInfo.userId) {
						that.onStatus = true
					}



				},
				function() {
					console.log("查询失败!");
				}
			);
		},
		//获取钥匙列表
		getKeylist() {
			var url = '/app/currentEntry/keyOperate/getBorrowKeyInfoList'
			var that = this
			let param = {
				keyOperateId: this.detail.keyOperateId
			}
			mui.neiosRequst.httpRequst(url, param,
				function(data) {
					that.keyList = data.data
				},
				function() {
					console.log("查询失败!");
				}
			);
		},
		//钥匙可否使用
		keyUsed(e) {
			var that = this
			var arr = this.keyList
			var keyManage = []
			arr.forEach(item => {
				keyManage.push({
					keyManageId: item.keyManageId,
					status: e
				})
			});


			that.maskShow();
			console.log("钥匙预借用参数=====",JSON.stringify(keyManage))		
			mui.neiosRequst.httpRequst('/app/currentEntry/keyOperate/keyIsUsed', keyManage,
				function(data) {
					console.log("钥匙提交了===========",JSON.stringify(keyManage))
					if (!data.data.isUsed) {
						that.sumbit(e);
						that.setNewDuty(e)
					} else {
						mui.toast(data.data.msg);
						that.maskClose();
						return
					};

				},
				function(data) {
					that.maskClose();
				}), 1
		},
		submitAdd() {
			var param = this.param
			param.saveType = 'I'
			if (this.$refs.personselectNext.person == '') {
				mui.toast('请选择审批人')
				return
			}

			param.nodeDealStaffCode = this.$refs.personselectNext.personids,
				param.nodeDealStaffName = this.$refs.personselectNext.person.split(']')[1]
			console.log(JSON.stringify(param))

			mui.neiosRequst.httpRequst('/app/currentEntry/keyOperate/saveOrUpdateKeyOperate', param,

				function(data) {
					if (data.code == 0) {
						mui.toast('操作成功')
						setTimeout(() => {
							var list = plus.webview.currentWebview().opener();
							//触发父页面的自定义事件(refresh),从而进行刷新
							mui.fire(list, 'refresh');
							mui.back()
						}, 1000);
					} else {
						mui.toast(data.msg)
					}
				},
				function(data) {

				}
			);
		},
		//保存-提交
		sumbit(e) {
			let _this = this;
			if (this.$refs.personselect.person == '' && e == 1) {
				_this.maskClose();
				mui.toast('请选择借用人')
				return
			} else if (this.remark == '' && e == 1) {
				_this.maskClose();
				mui.toast('请输入钥匙用途')
				return
			} else if (this.keyList.length == 0) {
				_this.maskClose();
				mui.toast('请添加钥匙信息')
				return
			} else if (this.$refs.personselectDuty.person == '' && e == 1) {
				_this.maskClose();
				mui.toast('请选择值班人')
				return
			}

			var arr = this.keyList
			var keyManage = []
			arr.forEach(item => {
				keyManage.push({
					keyManageId: item.keyManageId,
					status: e
				})
			})

			var keyList = this.keyList
			var stationKeyList = []
			var isShowStation = false
			var manageKeyList = []
			keyList.map((v, i) => {

				if (keyTypeStation.indexOf(v.keyType) != '-1') {

					stationKeyList.push(v)
					isShowStation = true
				}
				if (keyTypeManage.indexOf(v.keyType) != '-1') {
					manageKeyList.push(v)
				}
			})

			if (this.edit) {
				var keyOperate = {
					"dataStatus": 1,
					"dutyStaffCode": this.$refs.personselectDuty.personids,
					"dutyStaffName": this.$refs.personselectDuty.person.split(']')[1],
					"createBy": this.user.userId,
					"createStaffName": this.user.name,
					"operateType": '1',
					"dataSource": "NEIOS_APP"+localStorage.getItem("currVersion"),
					"client": "NEIOS",
					"operateStaff": '[' + this.detail.operateStaffCode + ']' + this.detail.operateStaffName,
					"workSheetCode": this.detail.workSheetCode,
					"remark": this.remark,
					"modifyBy": this.detail.modifyBy,
					"modifyStaffName": this.detail.modifyStaffName,
					"keyOperateId": this.detail.keyOperateId,
					"operateStaffCode": this.detail.operateStaffCode,
					"operateStaffName": this.detail.operateStaffName,
					"dutyStaff": '[' + this.detail.dutyStaffCode + ']' + this.detail.dutyStaffName,
					"workId": this.detail.workId,
					"operateTime": this.nowDate,
					"status": e,
					"stationCode": this.user.stationCode,
					"newStationCode": this.user.stationNewCode,
					"newAreaCode": this.user.companyNewCode,
					"areaCompanyCode": this.user.companyCode,
				}
			} else {
				var keyOperate = {
					"dataStatus": 1,
					"dutyStaffCode": this.$refs.personselectDuty.personids,
					"dutyStaffName": this.$refs.personselectDuty.person.split(']')[1],
					"createBy": this.user.userId,
					"createStaffName": this.user.name,
					"operateType": '1',
					"dataSource": "NEIOS_APP"+localStorage.getItem("currVersion"),
					"client": "NEIOS",
					"operateStaff": this.$refs.personselect.person || '',
					"workSheetCode": this.$refs.workTicket.person,
					"remark": this.remark,
					"modifyBy": this.user.userId,
					"modifyStaffName": this.user.name,
					"keyOperateId": this.keyOperateId,
					"operateStaffCode": this.$refs.personselect.personids || '',
					"operateStaffName": this.$refs.personselect.person.split(']')[1] || '',
					"dutyStaff": this.user.userName,
					"workId": "",
					"operateTime": this.nowDate,
					"status": e,
					"stationCode": this.user.stationCode,
					"newStationCode": this.user.stationNewCode,
					"newAreaCode": this.user.companyNewCode,
					"areaCompanyCode": this.user.companyCode,
				}
			}

			var param = {
				"saveType": this.saveType,
				"stationKeyList": stationKeyList,
				"manageKeyList": manageKeyList,
				"isSubmit": e == 1 ? true : false,
				"dataSource": "NEIOS_APP"+localStorage.getItem("currVersion"),
				"workType": "0202",
				"dutyApprove": this.$refs.personselectDuty.personids.toUpperCase() == this.user.userId
					.toUpperCase() ? false : true,
				"isShowDuty": this.$refs.personselectDuty.personids.toUpperCase() == this.user.userId
					.toUpperCase() ? false : true,
				"isShowStation": isShowStation,
				"isShowManage": false,
				"isBack": false,
				"isDone": false,
				"nodeDealStaffCode": this.$refs.personselectDuty.personids.toUpperCase() == this.user.userId
					.toUpperCase() ? this.user.userId : this.$refs.personselectDuty.personids,
				"nodeDealStaffName": this.$refs.personselectDuty.personids.toUpperCase() == this.user.userId
					.toUpperCase() ? this.user.name : this.$refs.personselectDuty.person.split(']')[1],
				"desc": ""
			}
			param.keyOperate = keyOperate
			param.keyOperateInfo = this.keyList
			param.keyManage = keyManage
			param.currentUser = this.user
			if (stationKeyList.length > 0 && e == 1) {
				param.isShowStation = true
				param.isShowManage = false
				if (this.$refs.personselectDuty.personids.toUpperCase() == this.user.userId.toUpperCase()) {
					this.param = param
					this.showSubmit = true
					this.maskClose();
					return
				}

			} else if (manageKeyList.length > 0 && e == 1) {
				param.isShowStation = false
				param.isShowManage = true
				if (this.$refs.personselectDuty.personids.toUpperCase() == this.user.userId.toUpperCase()) {
					this.param = param
					this.showSubmit = true
					this.maskClose();
					return
				}
			}
			console.log("======钥匙借用参数=====",JSON.stringify(param))

			console.log(JSON.stringify(param))
			if (this.$refs.personselectDuty.personids.toUpperCase() == this.user.userId.toUpperCase() && this
				.dutyInfo.dutyStaffCode == '') {
				this.setDuty()
			}
			mui.neiosRequst.httpRequst('/app/currentEntry/keyOperate/saveOrUpdateKeyOperate', param,
				function(data) {
					if (data.code == 0) {
						mui.toast('操作成功');
						setTimeout(() => {
							var list = plus.webview.currentWebview().opener();
							//触发父页面的自定义事件(refresh),从而进行刷新
							mui.fire(list, 'refresh');
							mui.back()
							_this.maskClose(1000);
						}, 500);
					} else {
						console.log(JSON.stringify(data))
						_this.maskClose();
						mui.toast(data.msg)
					}
				},
				function(data) {
					_this.maskClose();
				}, 1
			);
		},
		//重置
		reSet() {
			this.keyList = []
			this.remark = ''
			this.$refs.personselect.person = ''
		},
		//删除钥匙
		delKey(index) {
			var that = this
			var btnArray = ['取消', '确定'];
			mui.confirm('确定删除吗', '提示', btnArray, function(e) {
				if (e.index == 1) {
					if (!that.edit) {
						that.keyList.splice(index, 1)
					} else {
						that.keyList[index].dataStatus = 0
					}

				} else {}
			})
		},
		//扫码添加钥匙信息
		confrimKeyinfo() {
			var key = this.keyManageId.split(',')[0]
			var url = '/app/currentEntry/keyOperate/getKeyInfo'
			var that = this
			let param = {
				keyManageId: key,
			}
			mui.neiosRequst.httpRequst(url, param,
				function(data) {
					if (data.data == null) {
						mui.toast('暂无钥匙信息')
						return
					} else if (that.user.stationNewCode != data.data.newStationCode) {
						var btnArray = ['确定'];
						mui.confirm('该钥匙当前用户无借用权限', '提示', btnArray, function(e) {
							if (e.index == 1) {
								scan.close()

							} else {
								scan.close()

							}
						})

						return
					} else {
						var num = 0
						var info = data.data
						info.keyOperateInfoId = mui.neiosCommon.getUuidv4()
						info.lendingOperateId = that.keyOperateId
						info.client = 'NEIOS'
						info.dataSource = 'NEIOS_APP'+localStorage.getItem("currVersion")
						if (that.keyList.length == 0) {
							that.keyList.push(info)
						} else {
							that.keyList.forEach(item => {
								if (that.keyManageId == item.keyCode) {
									num += 1
								}
							});
							if (num == 0) {
								that.keyList.push(info)
							}
						}
					}
					that.showAdd = false
				},
				function() {
					console.log("查询失败!");
				}
			);
		},
		//确认钥匙信息
		confirmKey() {
			if (this.keyNum == '') {
				mui.toast('请输入钥匙编号')
				return
			}
			var url = '/app/currentEntry/keyOperate/getKeyByCode'
			var that = this
			let param = {
				stationNewCode: this.user.stationNewCode,
				keyCode: this.keyNum
			}
			mui.neiosRequst.httpRequst(url, param,
				function(data) {
					if (data.data == null) {
						mui.toast('暂无钥匙信息')
						return
					}
					var num = 0
					var info = data.data
					info.keyOperateInfoId = mui.neiosCommon.getUuidv4()
					info.lendingOperateId = that.keyOperateId
					info.client = 'NEIOS'
					info.dataSource = 'NEIOS_APP'+localStorage.getItem("currVersion")
					if (that.keyList.length == 0) {
						that.keyList.push(info)
					} else {
						that.keyList.forEach(item => {
							if (that.keyNum == item.keyCode) {
								num += 1
							}
						});
						if (num == 0) {
							that.keyList.push(info)
						}
					}
					that.showAdd = false
					that.keyNum = ''
				},
				function() {
					console.log("查询失败!");
				}
			);
		},
		//获取当前时间
		getDate() {
			var date = new Date()
			var year = date.getFullYear()
			var month = date.getMonth() + 1
			var day = date.getDate()
			var hour = date.getHours()
			var min = date.getMinutes()

			if (month.toString().length < 2) {
				month = '0' + month
			}
			if (day.toString().length < 2) {
				day = '0' + day
			}
			if (hour.toString().length < 2) {
				hour = '0' + hour
			}
			if (min.toString().length < 2) {
				min = '0' + min
			}
			this.nowDate = year + '-' + month + '-' + day + ' ' + hour + ':' + min
		},
		//返回上一页
		goBack() {
			scan.close()
			mui.back()
		},
		//更多按钮
		showMore() {
			this.showMorebtn ? this.showMorebtn = false : this.showMorebtn = true
		},
		//阻止事件冒泡
		clickStop() {

		},
		//选择是否为值班人
		checkOnstatus() {
			console.log(this.onStatus)
			this.onStatus ? this.onStatus = false : this.onStatus = true

		},
		//点击菜单
		menuClick(e) {
			var that = this
			if (e.name == '我值班') {
				if (this.dutyInfo.dutyStaffCode == this.userInfo.userId) {
					mui.toast('你已经是值班人')
					return
				}
				var btnArray = ['否', '是'];
				mui.confirm('确定设置自己为值班人吗', '提示', btnArray, function(e) {
					if (e.index == 1) {
						that.setDuty()
					} else {}
				})
			} else {
				this.showMenu = false
				this.navTo(e.path)
			}
		},
		//左上角菜单显示隐藏
		showMenulist() {
			this.showMenu ? this.showMenu = false : this.showMenu = true
		},
		navTo(e) {
			mui.openWindow({
				url: e,
				id: e,
			});
		}
	},

})


scan = null; //扫描对象
mui.plusReady(function() {
	mui.init();

});
var able = true
$('#scan-btn').on("click", function(e) {
	if (able) {
		able = false
		startRecognize();
		setTimeout(function() {
			able = true
		}, 1000);
	}

})
$('#back-btn').on("click", function(e) {
	if (scan) {
		scan.close()
	}
	mui.back()

})

function startRecognize() {
	try {
		var filter;
		//自定义的扫描控件样式
		var styles = {
			top: '100px',
			left: '0px',
			width: '100%',
			height: '500px',
			position: 'static',
		}
		//扫描控件构造
		scan = plus.barcode.create('bcid', filter, styles);
		scan.onmarked = onmarked;
		scan.onerror = onerror;
		plus.webview.currentWebview().append(scan);
		scan.start();

	} catch (e) {
		alert("出现错误啦:\n" + e);
	}
};

function onerror(e) {
	alert(e);
};

function onmarked(type, result) {
	var text = '';
	switch (type) {
		case plus.barcode.QR:
			text = 'QR: ';
			break;
		case plus.barcode.EAN13:
			text = 'EAN13: ';
			break;
		case plus.barcode.EAN8:
			text = 'EAN8: ';
			break;
	}
	//扫描成功之后的处理
	mui.toast('扫描成功')
	console.log(result)
	projectVM.keyManageId = result
	projectVM.confrimKeyinfo()
	scan.close();
	javascript: window.history.back(-1);
};
